<template>
  <view
    class="hb-flex hb-items-center hb-py-4 hb-border-solid hb-border-[#EBEDF0]"
    :class="{ 'hb-border-b': showSetting }"
    @click="handleOpenDocument"
  >
    <TmIcon
      class="hb-flex-shrink-0"
      :name="`ali-icon ${getFileIcon(item.fileSuffix).icon}`"
      :follow-theme="false"
      :color="getFileIcon(item.fileSuffix).color"
      :font-size="80"
    />
    <view class="hb-ml-2 hb-flex-1 hb-flex hb-flex-col hb-justify-between">
      <TmText _class="text-overflow-1 hb-font-bold" :label="item.fileName" :font-size="28" />
      <view class="hb-flex hb-items-center hb-mt-1">
        <TmText :label="fileSizeConversion(item.fileSize)" :font-size="24" color="#969799" />
        <TmText class="hb-mx-1" label="·" color="#969799" :font-size="24" />
        <TmText :label="formatToDate(item.updateTime)" :font-size="24" color="#969799" />
      </view>
    </view>
    <view
      v-if="showSetting"
      class="hb-pl-4 hb-h-10 hb-flex hb-items-center"
      @click.stop="handleSetting(item)"
    >
      <TmIcon name="ali-icon icon-shezhi1" color="#969799" :font-size="32" />
    </view>
  </view>
</template>

<script setup lang="ts">
  import { formatToDate } from '@/utils/dateUtil';
  import { getFileIcon } from '@/utils';
  import { KnowledgeBaseFileListResult } from '@/api/knowledgeBase/types';
  import { useUpload } from '@/hooks/file/useUpload';

  const { openDocument } = useUpload();
  const emit = defineEmits<{
    (e: 'refresh'): void;
  }>();

  /** 文件大小转换, 当前默认单位是Bytes,转换成MB */
  function fileSizeConversion(size: number) {
    if (size === 0) return '0 B';

    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    const digitGroups = Math.floor(Math.log10(size) / Math.log10(1024));

    // 限制在可用单位范围内
    const unitIndex = Math.min(digitGroups, units.length - 1);
    const convertedSize = size / Math.pow(1024, unitIndex);

    // 根据大小决定小数位数
    const decimalPlaces = unitIndex > 0 ? 2 : 0;

    return convertedSize.toFixed(decimalPlaces) + ' ' + units[unitIndex];
  }

  const props = withDefaults(
    defineProps<{
      item: KnowledgeBaseFileListResult;
      showSetting: boolean;
    }>(),
    {
      showSetting: false,
    },
  );

  const handleOpenDocument = () => {
    const item = props.item;
    openDocument({ filePath: item.filePathUrl, fileType: item.fileSuffix });
  };

  /** 文件设置 */
  const handleSetting = (item: KnowledgeBaseFileListResult) => {
    navigateTo({
      name: 'fileResourceSetting',
      options: { id: item.id, success: () => emit('refresh') },
    });
  };
</script>

<style scoped></style>
